(function() {"use strict";var __module = CC_EDITOR ? module : {exports:{}};var __filename = 'preview-scripts/assets/scripts/pomelo/PomeloMgr.js';var __require = CC_EDITOR ? function (request) {return cc.require(request, require);} : function (request) {return cc.require(request, __filename);};function __define (exports, require, module) {"use strict";
cc._RF.push(module, 'b5830cNHENKbafIrvbVuoLl', 'PomeloMgr', __filename);
// scripts/pomelo/PomeloMgr.js

"use strict";

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var nop = function nop() {};

function rpc(event, data) {
    var param = {};
    event && (param.e = event);
    data && (param.d = data);
    pomelo.request('room.roomHandler.z', param, function (msg) {
        if (Object.keys(msg).length > 0) {
            console.log("发送请求失败: " + msg.code);
        }
    });
}

var PomeloMgr = function () {
    function PomeloMgr() {
        _classCallCheck(this, PomeloMgr);
    }

    _createClass(PomeloMgr, [{
        key: "init",
        value: function init() {
            if (consts.isYiLe) {
                //牛气冲天地址
                this.url = window.consts.yileUri;
            } else {
                //胡大王地址
                // HTTP_SERVER = 'http://39.108.151.212:9000';
                // HTTP_SERVER = "http://192.168.0.103:9000";
                this.url = window.consts.uri;
            }

            console.log(consts.isYiLe + ":服务器地址:" + this.url);
        }

        /**
         *
         */

    }, {
        key: "httpGET",
        value: function httpGET(path, data, handler, extraUrl) {
            var xhr = cc.loader.getXMLHttpRequest();
            var isTimeout = false;
            var str = "?";
            for (var k in data) {
                if (str != "?") str += "&";
                str += k + "=" + data[k];
            }
            if (extraUrl == null) extraUrl = this.url;
            var requestURL = extraUrl + path + (str === '?' ? '' : encodeURI(str));
            // console.log("RequestURL:" + requestURL);
            xhr.open("GET", requestURL, true);
            //设置请求头
            if (cc.sys.isNative) xhr.setRequestHeader("Accept-Encoding", "gzip,deflate", "text/html;charset=UTF-8");

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && !isTimeout) {
                    isTimeout = true;
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // console.log("http res(" + xhr.responseText.length + "):" + xhr.responseText);
                        var ret = xhr.responseText;
                        try {
                            ret = JSON.parse(xhr.responseText);
                            ret.code = parseInt(ret.code);
                        } catch (e) {
                            handler({ code: -888, errmsg: "不是json对象" });
                            return;
                        }
                        console.log(path, {
                            msgLen: xhr.responseText.length,
                            url: requestURL,
                            result: ret
                        });
                        if (handler !== null) handler(ret);
                    } else {
                        console.log(path, {
                            url: requestURL,
                            result: { code: 41, errmsg: "服务器忙，请稍后在试" }
                        });
                        handler({ code: 41, errmsg: "服务器忙，请稍后在试" });
                    }
                }
            };
            xhr.send();

            setTimeout(function () {
                if (!isTimeout) {
                    isTimeout = true;
                    handler({ code: 42, errmsg: "连接失败，请稍后在试" });
                }
            }, 5000);
            return xhr;
        }

        /**
         * 发送
         * @param options
         * @param cb
         */

    }, {
        key: "httpSend",
        value: function httpSend(options, cb) {
            cb = cb || nop;
            var xhr = cc.loader.getXMLHttpRequest();
            var isTimeout = false;
            var url = options.url || this.url;
            var path = options.path || '/';
            var context = '';
            var URI = '';

            if (!/post/i.test(options.method)) {
                context = this.queryString(options.data);
            }

            URI = url + path + context;

            console.log(URI);

            xhr.open(options.method || "GET", URI, true);

            //设置请求头
            if (cc.sys.isNative && /get/i.test(options.method)) {
                xhr.setRequestHeader("Accept-Encoding", "gzip,deflate", "text/html;charset=UTF-8");
            }
            if (/post/i.test(options.method)) {
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            }

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && !isTimeout) {
                    isTimeout = true;
                    if (xhr.status >= 200 && xhr.status < 300) {
                        var ret = xhr.responseText;
                        try {
                            ret = JSON.parse(xhr.responseText);
                            ret.code = parseInt(ret.code);
                        } catch (e) {
                            ret = {
                                code: -888,
                                msg: "不是json对象",
                                result: xhr.responseText
                            };
                        }

                        console.log(path, {
                            url: URI,
                            params: options.data,
                            msgLen: xhr.responseText.length,
                            result: ret
                        });

                        if (cb !== null) cb(parseInt(ret.code), ret);
                    } else {
                        console.log(path, {
                            url: URI,
                            result: [41, "服务器忙，请稍后在试"]
                        });
                        cb(41, "服务器忙，请稍后在试");
                    }
                }
            };

            if (/post/i.test(options.method)) {
                xhr.send("param=" + JSON.stringify(options.data || {}));
            } else {
                xhr.send();
            }

            setTimeout(function () {
                if (!isTimeout) {
                    isTimeout = true;
                    console.log(path, {
                        url: URI,
                        result: { code: 42, errmsg: "连接超时，请稍后在试" }
                    });
                    cb(42, "连接超时，请稍后在试");
                }
            }, 10000);
        }

        /**
         * 将参数转找成链接形式
         * @param context
         * @return {*}
         */

    }, {
        key: "queryString",
        value: function queryString(context) {
            if (!context || (typeof context === "undefined" ? "undefined" : _typeof(context)) !== "object") {
                return "";
            }
            var str = "?";
            for (var k in context) {
                str === "?" || (str += "&");
                str += k + "=" + context[k];
            }
            return str;
        }

        /**
         * post请求
         * @param event  接口名
         * @param data   数据对象
         * @param cb     回调cb(code, msg);
         */

    }, {
        key: "post",
        value: function post(event, data, cb) {
            data.account = cc.user.account;
            data.sign = cc.user.sign;
            data.cid = consts.cid;
            data.uid = cc.user.uid;
            this.httpSend({
                method: "POST",
                path: '/' + event,
                data: data
            }, cb);
        }

        /**
         * 检查版本信息
         * @param data
         * @param cb
         */

    }, {
        key: "checkVersion",
        value: function checkVersion(data, cb) {
            this.httpSend({
                method: "GET",
                path: '/check_version',
                data: data
            }, cb);
        }

        /**
         *
         * @param code
         * @param os
         * @param cb
         */

    }, {
        key: "wechat_auth",
        value: function wechat_auth(code, os, cb) {
            this.httpGET("/wx_login", { code: code, os: os }, cb);
        }

        /**
         * 更新地理位置
         */

    }, {
        key: "updateLocation",
        value: function updateLocation() {
            console.log("更新地理位置" + this.isLocation);
            if (!this.isLocation) {
                var address = cc.vv.map.getAddrStr();
                var self = this;
                if (address && address.errcode == 0) {
                    this.httpSend({
                        method: "POST",
                        path: "/update_location",
                        data: {
                            account: cc.user.account,
                            sign: cc.user.sign,
                            location: JSON.stringify(address)
                        }
                    }, function (code, ret) {
                        if (code === 200) {
                            console.log("提交位置成功");
                            self.isLocation = true;
                        } else {
                            console.log(ret.code + "提交位置失败：" + cc.Code[ret.code]);
                        }
                    });
                }
            }
        }

        /**
         * 绑定代理
         * @param code 代理邀请码
         * @param cb   回调
         */

    }, {
        key: "bindDealer",
        value: function bindDealer(code, cb) {
            this.httpSend({
                path: "/bind_dealer",
                data: {
                    account: cc.user.account,
                    sign: cc.user.sign,
                    user_code: code
                }
            }, cb);
        }

        /**
         * 支付接口
         * @param id 商品id
         * @param cb 回调
         */

    }, {
        key: "buy",
        value: function buy(id, cb) {
            this.httpSend({
                path: "/buy_diamond",
                data: {
                    account: cc.user.account,
                    sign: cc.user.sign,
                    user_id: cc.user.uid,
                    os: cc.sys.os === cc.sys.OS_IOS ? "ios" : "android",
                    pay_type: "30", //微信支付，22=支付宝支付
                    id: id
                }
            }, cb);
        }

        /**
         * 查询订单是否支付成功
         * @param orderSn 订单号
         * @param cb
         */

    }, {
        key: "queryOrder",
        value: function queryOrder(orderSn, cb) {
            this.httpSend({
                path: "/query_order",
                data: {
                    account: cc.user.account,
                    sign: cc.user.sign,
                    order_sn: orderSn
                }
            }, cb);
        }

        /**
         * 获取房间列表
         * @param cb
         */

    }, {
        key: "getRoomList",
        value: function getRoomList(cb) {
            this.httpGET("/getRoomList", {
                uid: cc.user.uid,
                account: cc.user.account,
                sign: cc.user.sign
            }, function (data) {
                cb(data.code, data.res);
            });
        }

        /**
         * 获取一个房间的战绩
         * @param cb
         */

    }, {
        key: "getOneHistory",
        value: function getOneHistory(uuid, cb) {
            this.httpGET("/getOneHistory", {
                account: cc.user.account,
                sign: cc.user.sign,
                uuid: uuid
            }, function (data) {
                cb(data.code, data.result);
            });
        }

        /**
         * 获取历史记录
         */

    }, {
        key: "getHistory",
        value: function getHistory(cb) {
            this.httpGET("/getHistory", {
                uid: cc.user.uid,
                account: cc.user.account,
                sign: cc.user.sign,
                page: 0
            }, function (data) {
                cb(data.code, data.res);
            });
        }
    }, {
        key: "getHistoryDetail",
        value: function getHistoryDetail(id, cb) {
            this.httpGET("/getRoomHistory", {
                id: id,
                account: cc.user.account,
                sign: cc.user.sign
            }, cb);
        }

        /**
         * 获取身份信息
         * @param account
         * @param cb
         */

    }, {
        key: "guest_auth",
        value: function guest_auth(account, cb) {
            this.httpGET("/guest", { account: account }, cb);
        }

        /**
         * 获取账户信息
         * @param account
         * @param sign
         * @param cb
         */

    }, {
        key: "getInfo",
        value: function getInfo(account, sign, cb) {
            this.httpGET("/get_user_info", { account: account, sign: sign }, cb);
        }

        /**
         * 创建房间
         * @param data
         * @param cb
         */

    }, {
        key: "createRoom",
        value: function createRoom(data, cb) {
            this.httpSend({
                path: '/create_infinite_room',
                method: "POST",
                data: data
            }, cb);
        }

        /**
         * 加入房间
         * @param rid 房间号
         * @param cb
         */

    }, {
        key: "joinRoom",
        value: function joinRoom(rid) {
            cc.utils.openLoading("玩命加入房间: " + rid);
            this.httpSend({
                path: '/join_infinite_room',
                method: "POST",
                data: {
                    account: cc.user.account,
                    sign: cc.user.sign,
                    uid: cc.user.uid,
                    rid: rid,
                    cid: consts.cid
                }
            }, function (code, msg) {
                console.log(arguments);
                if (code === 200) {
                    console.log("开始连接", rid);
                    cc.pomelo.connect(msg.host, msg.port, rid);
                } else {
                    cc.utils.openErrorTips(code);
                }
            });
        }

        /**
         * 连接房间服务器
         * @param host
         * @param port
         * @param rid
         */

    }, {
        key: "connect",
        value: function connect(host, port, rid) {
            var self = this;
            this.host = host;
            this.port = port;
            window.pomelo.removeAllListeners();

            function join(cb) {
                self.httpSend({
                    path: '/join_infinite_room',
                    method: "POST",
                    data: {
                        account: cc.user.account,
                        sign: cc.user.sign,
                        uid: cc.user.uid,
                        rid: rid,
                        cid: consts.cid
                    }
                }, function (code, msg) {
                    if (code === 200) {
                        init(cb);
                    } else if (parseInt(code) === 5001) {
                        cc.pomelo.emit("notExists");
                    } else {
                        cc.utils.openErrorTips(code, function () {
                            cc.director.loadScene("hall");
                        });
                    }
                });
            }

            /**
             * 初始连接服务器
             */
            function init(cb) {
                window.pomelo.init({
                    host: host,
                    port: port,
                    log: true,
                    reconnect: false
                }, function () {
                    login(cb);
                    window.pomelo.on("disconnect", disconnect);
                });
            }

            /**
             * 登录房间
             */
            function login(cb) {
                window.pomelo.request('room.roomHandler.login', {
                    account: cc.user.account,
                    sign: cc.user.sign,
                    rid: rid,
                    uid: cc.user.uid
                }, function (msg) {
                    if (isNaN(msg)) {
                        var code = parseInt(msg.code);
                        var type = parseInt(msg.type); //游戏类型
                        if (code === 200) {
                            cb(type);
                        } else {
                            cc.utils.openErrorTips(code, function () {
                                cc.director.loadScene("hall");
                            });
                            self.disconnect();
                        }
                    } else {
                        cc.utils.openErrorTips(msg, function () {
                            cc.director.loadScene("hall");
                        });
                        self.disconnect();
                    }
                });
            }

            /**
             * 掉线触发函数
             */
            function disconnect() {
                console.log("掉线");
                self.disconnectCb && self.disconnectCb(); //调用离线回调
                window.pomelo.off('disconnect');
                cc.utils.openLoading("玩命连接...");
                setTimeout(function () {
                    join(function () {
                        self.getRoomInfo(); //获取房间数据
                        cc.utils.closeTips();
                    });
                }, 100);
            }

            init(function (type) {
                if (type === 5) {
                    cc.director.loadScene("PDKScene");
                } else {
                    if (type === 6) {
                        cc.director.loadScene("PSZScene");
                    } else {
                        cc.director.loadScene("niuniu");
                    }
                }
            });
        }

        //断开连接

    }, {
        key: "disconnect",
        value: function disconnect(cb) {
            console.log("主动断开连接");
            cb = cb || nop;
            cc.pomelo.off('disconnect');
            window.pomelo.disconnect(cb);
        }

        /**
         * 设置一个离线监听函数
         */

    }, {
        key: "setDisconnect",
        value: function setDisconnect(cb) {
            this.disconnectCb = cb;
        }

        //添加监听

    }, {
        key: "on",
        value: function on(route, cb) {
            pomelo.on(route, cb);
        }

        //移除监听

    }, {
        key: "off",
        value: function off(route, cb) {
            pomelo.off(route, cb);
        }

        //发送事件

    }, {
        key: "emit",
        value: function emit(event, data) {
            window.pomelo.emit(event, data);
        }

        /**
         * 获取房间数据
         */

    }, {
        key: "getRoomInfo",
        value: function getRoomInfo() {
            rpc('roomInfo');
        }

        /**
         * 解散房间
         * 只有房主才能解散房间
         * @param uid 玩家uid
         */

    }, {
        key: "dismiss",
        value: function dismiss() {
            rpc('dismiss');
        }
    }, {
        key: "okDismiss",
        value: function okDismiss() {
            rpc('okDismiss');
        }
    }, {
        key: "notDismiss",
        value: function notDismiss() {
            rpc('notDismiss');
        }

        /**
         * 申请解散房间
         * 只有正在玩的人才能解散房间
         */

    }, {
        key: "applyDismiss",
        value: function applyDismiss() {
            rpc('applyDismiss');
        }

        /**
         * 离开房间
         * 只有游客和房间未开始时，才能离开房间
         * @param uid  玩家uid
         */

    }, {
        key: "leave",
        value: function leave() {
            rpc('leave', "data");
        }

        /**
         * 坐下
         */

    }, {
        key: "sitDown",
        value: function sitDown() {
            rpc('sitDown');
        }

        /**
         * 准备
         */

    }, {
        key: "ready",
        value: function ready() {
            rpc('ready');
        }

        /**
         * 取消准备
         */

    }, {
        key: "unready",
        value: function unready() {
            rpc('unready');
        }

        /**
         * 开始
         */

    }, {
        key: "start",
        value: function start() {
            rpc('gameStart');
        }

        /**
         * 发送表情
         */

    }, {
        key: "emoji",
        value: function emoji(id) {
            rpc('emoji', id);
        }

        /**
         * 聊天
         */

    }, {
        key: "chat",
        value: function chat(str) {
            if (str === '' || str === undefined || str === null) {
                console.log("聊天信息不能为空 chat = " + str);
            } else {
                rpc('chat', str);
            }
        }

        /**
         * 语音
         * @param msg 语音
         * @param time 语音时间
         */

    }, {
        key: "voice",
        value: function voice(msg, time) {
            rpc('voice', [msg, time]);
        }

        /**
         * 常用语
         */

    }, {
        key: "cWord",
        value: function cWord(id) {
            rpc('cWord', id);
        }

        /**
         * 发送动画，扔的动画
         * @param suid 开始位置
         * @param euid 结束位置
         * @param id 动画id
         */

    }, {
        key: "animate",
        value: function animate(suid, euid, id) {
            rpc('animate', [suid, euid, id]);
        }

        /**
         * 设置托管
         */

    }, {
        key: "tuoGuang",
        value: function tuoGuang() {
            rpc('tuoGuang');
        }

        /**
         * 发送消息
         * @param event
         * @param data
         */

    }, {
        key: "send",
        value: function send(event, data) {
            var param = {};
            event && (param.e = event);
            data && (param.d = data);
            window.pomelo.request('room.roomHandler.s', param, function (msg) {
                if (Object.keys(msg).length > 0) {
                    console.log("发送请求失败: " + msg.code);
                }
            });
        }
    }]);

    return PomeloMgr;
}();

module.exports = new PomeloMgr();

cc._RF.pop();
        }
        if (CC_EDITOR) {
            __define(__module.exports, __require, __module);
        }
        else {
            cc.registerModuleFunc(__filename, function () {
                __define(__module.exports, __require, __module);
            });
        }
        })();
        //# sourceMappingURL=PomeloMgr.js.map
        